<?php


namespace app\library\model;

use Medoo\Medoo;
use app\library\facade\Logger;

class Medo extends Medoo
{
    protected $pool;

    protected $slave;

    protected $isRead;

    public function __construct($config = null)
    {
        $config = \Yaf\Registry::get('config');
        $this->pool = \Yaf\Registry::get('mysql');
        if ($config['mysql.rw_separate']) {
            $this->slave = array_rand(\Yaf\Registry::get('mysql_slave'));
        }
    }

    public function exec($query, $map = [])
    {
        $this->getPdo();
        $res = parent::exec($query, $map);
        $this->release();
        return $res;
    }


    public function get($table, $join = null, $columns = null, $where = null)
    {
        $this->setPool();
        return parent::get($table, $join, $columns, $where); // TODO: Change the autogenerated stub
    }

    private function getPdo()
    {
        if ($this->isRead) {
            $this->pdo = $this->slave->get();
        } else {
            $this->pdo = $this->pool->get();
        }
    }

    private function release()
    {
        if ($this->isRead) {
            $this->setPool(false);
            $this->slave->put($this->pdo);
        } else {
            $this->pool->put($this->pdo);
        }
    }

    public function setPool($bool = true)
    {
        $this->isRead = $bool;
    }

}